<template>
	<view class="step-item">
		<!-- 进度条部分保持不变 -->

		<view class="activity-title">
			<text class="title-text">公益跑步活动</text>
			<text class="fee-note">注：活动上架费5元</text>
		</view>

		<!-- 报名套餐设置 -->
		<view class="section">
			<view class="section-title">报名套餐设置</view>
			<!-- <u-loading mode="circle" v-if="!activitySpecs.spec_value_list" /> -->
			<view class="package-list">
				<view v-if="activitySpecs && activitySpecs.spec_value_list">
					<view 
						class="package-item" 
						v-for="(spec, index) in activitySpecs.spec_value_list || []" 
						:key="index"
					>
						<view class="package-content">
							<text class="requirement">人员要求：{{ formatSpecValues(spec.spec_value_str) }}</text>
							<view class="price-info">
								<text class="original-price">¥{{ spec.original_price }}</text>
								<text class="current-price">¥{{ spec.price }}</text>
								<text class="discount">({{
									Math.round((spec.price / spec.original_price) * 100) / 10
								}}折)</text>
								<!-- <text class="stock">库存：{{ spec.stock }}</text> -->
							</view>
						</view>
					</view>
				</view>
				<view v-else class="empty-tips">暂无套餐数据</view>
			</view>
			<view class="add-package" @click="addPackage">
				<u-icon name="plus" size="24" color="#0DC160"></u-icon>
				<text>添加/编辑报名套餐</text>
			</view>
		</view>

		<!-- 收益比例设置 -->
		<view class="section">
			<view class="section-title">收益比例设置</view>
			<view class="profit-settings">
				
				<view class="setting-group">
					<view class="sub-title">分享人设置</view>
					<view class="radio-group">
						<radio-group @change="setShareType">
							<label class="radio-item horizontal">
								<radio value="1" :checked="shareType === 1" /> 比例（%）
							</label>
							<label class="radio-item horizontal">
								<radio value="2" :checked="shareType === 2" /> 固定金额（元）
							</label>
						</radio-group>
					</view>
					<view class="input-group">
						<input 
							v-if="shareType === 1"
							type="number" 
							placeholder="分享人比例" 
							v-model="shareRatio"
						/>
						<input 
							v-else
							type="number" 
							placeholder="分享人固定金额" 
							v-model="shareFixed"
						/>
						<text class="unit">{{ shareType === 1 ? '%' : '元' }}</text>
					</view>
				</view>

				
				<!-- <view class="setting-group">
					<view class="sub-title">陪伴师设置</view>
					<view class="radio-group">
						<radio-group @change="setImplementType">
							<label class="radio-item horizontal">
								<radio value="1" :checked="implementType === 1" /> 比例（%）
							</label>
							<label class="radio-item horizontal">
								<radio value="2" :checked="implementType === 2" /> 固定金额（元）
							</label>
						</radio-group>
					</view>
					<view class="input-group">
						<input 
							v-if="implementType === 1"
							type="number" 
							placeholder="陪伴师比例" 
							v-model="implementRatio"
						/>
						<input 
							v-else
							type="number" 
							placeholder="陪伴师固定金额" 
							v-model="implementFixed"
						/>
						<text class="unit">{{ implementType === 1 ? '%' : '元' }}</text>
					</view>
				</view> -->
			</view>
		</view>

		<!-- 收益计算结果 -->
		<view class="section">
			<view class="section-title">收益计算结果</view>
			<view class="income-result" v-if="minProfit && maxProfit">
				<text>最低收益：¥{{ minProfit || 0 }} - 最高收益：¥{{ maxProfit || 0 }}</text>
			</view>
			<view v-else-if="!loading" class="income-tips">
				<text>请先完成收益比例设置</text>
			</view>
			<view class="loading-wrapper" v-if="loading">
				<u-loading mode="circle" color="#0DC160"></u-loading>
				<text class="loading-text">正在计算收益...</text>
			</view>
		</view>

		<!-- 优惠券设置 -->
		<view class="section">
			<view class="section-title">优惠券设置</view>
			<view class="coupon-settings">
				<view class="coupon-item">
					<u-checkbox class="enable-coupon" v-model="isCouponEnabled" active-color="#0DC160">
						<text>启用优惠券</text>
					</u-checkbox>
				</view>
				<view class="coupon-item">
					<input type="number" placeholder="请输入" placeholder-class="placeholder" :disabled="!isCouponEnabled" />
					<text class="unit">元</text>
				</view>
			</view>
		</view>

		<!-- 提交按钮 -->
		<view class="submit-btn">
			<button class="btn-primary" @click="submit">提交审核</button>
		</view>

		<!-- 点击添加/编辑报名套餐 -->
		<u-popup v-model="showPopup" mode="bottom" :closeable="true">
			<view class="popup-container">
				<view class="popup-header">
					<view class="popup-wrapper">
						<text class="popup-title">添加报名套餐规格</text>
					</view>

					<!--          <view class="close-icon" @click="showPopup = false">
            <u-icon name="close" size="20"></u-icon>
          </view> -->
				</view>

				<view class="popup-content">
					<!-- 规格设置 -->
					<view class="spec-section">
						<view class="section-header">
							<text>规格设置</text>
							<text class="limit-text">(限制最多3个规格)</text>
							<view class="add-spec" @click="addSpecItem">
								<text>+添加规格项</text>
								<!-- <u-icon name="plus" color="#0DC160" size="14"></u-icon> -->
							</view>
						</view>

						<view class="spec-list">
							<view class="spec-item" v-for="(item, index) in specList" :key="index">
								<view class="spec-name-section">
									<view class="spec-name-header">
										<text>规格名称</text>
										<image src="/static/images/htqrdel.png" mode="" style="width: 26rpx; height: 24rpx" @click="deleteSpec(index)"></image>
									</view>
									<input type="text" class="spec-name-input" placeholder="请输入" v-model="item.name" />
								</view>
								
								<view class="spec-values-section">
									<view class="spec-values-header">
										<text>规格值</text>
										<view class="add-value" @click="addSpecValue(index)">
											<text>+添加</text>
										</view>
									</view>
									<view class="value-list">
										<view class="value-item" v-for="(value, vIndex) in item.spec_list" :key="vIndex">
											<input type="text" placeholder="请输入" v-model="value.value" />
											<image src="/static/images/htqrdel.png" mode="" style="width: 26rpx; height: 24rpx" @click="deleteValue(index, vIndex)"></image>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>

					<!-- 报名套餐价格设置 -->
					<view class="price-section">
						<view class="section-header">
							<text>报名套餐价格设置</text>
						</view>
						<view class="price-table">
							<view class="table-header">
								<text>规格名</text>
								<text>原价</text>
								<text>售价</text>
							</view>
							<view class="table-row" v-for="(spec, index) in priceList" :key="index">
								<text class="spec-name">{{ spec.spec_value_str }}</text>
								<input type="number" placeholder="请输入" v-model="spec.original_price" />
								<input type="number" placeholder="请输入" v-model="spec.price" />
							</view>
						</view>
					</view>
				</view>

				<view class="popup-footer">
					<button class="confirm-btn" @click="confirmSpecs">确认</button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import { publishActivity, activityIncome, trainerList } from '@/api/launchevent'
import { mapState } from 'vuex'
import store from 'store'
export default {
	props: {
		activityId: Number,
		activityState: Number
	},
	data() {
		return {
			showPopup: false,
			packages: [1, 2], // 示例套餐数据
			shareType: 1, // 1-比例 2-固定金额
			implementType: 1, // 1-比例 2-固定金额
			shareRatio: '', // 分享人比例值
			shareFixed: '', // 分享人固定金额
			implementRatio: '', // 陪伴师比例值
			implementFixed: '', // 陪伴师固定金额
			isCouponEnabled: false, // 新增数据属性，用于记录优惠券是否启用
			// 新增数据
			specList: [], // 规格列表
			priceList: [], // 价格设置列表
			loading: false,
			minProfit: null,
			maxProfit: null,
			trainerId: '',
			activitySpecs: {}
		};
	},
	computed: {
		...mapState({
			
		}),
		allSettings() {
			return {
				shareType: this.shareType,
				shareRatio: this.shareRatio,
				shareFixed: this.shareFixed,
				implementType: this.implementType,
				implementRatio: this.implementRatio,
				implementFixed: this.implementFixed
			}
		}
	},
	watch: {
		allSettings: {
			handler() {
				this.debouncedCalculateIncome();
			},
			deep: true,
			immediate: false
		},
		specList: {
			handler() {
				this.setPriceList();
			},
			deep: true,
			immediate: true
		},
		priceList: {
			handler(newVal) {
				console.log(1111111111111,newVal)
				this.activitySpecs.spec_value_list = newVal;
			},
			deep: true
		},
		activitySpecs: {
			handler(newVal) {
				console.log(2222222222,newVal)
				this.priceList = newVal;
			},
			deep: true
		}
	},
	methods: {
		setPriceList(){
			const { priceList, specList } = this
			console.log(priceList, specList, '#####')

			const inSpecList = specList.map((item) => item.spec_list)
			const newData = this.getTableData(inSpecList)
			console.log(newData, '******')

			const rawData = JSON.parse(JSON.stringify(priceList))
			console.log(rawData, '0000000')

			const rawObject = {}
			rawData.forEach((item) => {
					if (item.spec_value_str !== undefined) {
							rawObject[item.spec_value_str] = item
					}
			})
			console.log(rawObject, '9999999')

			this.priceList = newData.map((item) =>
					rawObject[item.spec_value_str]
							? {
										...rawObject[item.spec_value_str],
										value: item.value,
										ids: item.ids
								}
							: item
			)
		},
		getTableData(arr) {
				arr = JSON.parse(JSON.stringify(arr))
				return arr.reduce(
						(prev, next) => {
								const newArr = []
								for (let i = 0; i < prev.length; i++) {
										if (!next.length) {
												newArr.push(this.setFields(prev[i], {}))
										}
										for (let j = 0; j < next.length; j++) {
												next[j].ids = j
												newArr.push(this.setFields(prev[i], next[j]))
										}
								}
								return newArr
						},
						[{}]
				)
		},
		setFields(prev, next) {
			let valueArr = [prev, next]
			valueArr = valueArr.filter(item => item.value !== undefined)
			const ids = this.flatten(valueArr.map(item => item.ids)).join()
			const value = this.flatten(valueArr.map(item => item.value))
			return {
					id: prev.id ? prev.id : '',
					ids: ids,
					value,
					spec_value_str: value.join(),
					price: prev.price ? prev.price : '',
					original_price: prev.original_price ? prev.original_price : '',
					stock: prev.stock ? prev.stock : '',
				}
		},
		flatten(arr) {
		    return arr.reduce((result, item) => {
		        return result.concat(Array.isArray(item) ? this.flatten(item) : item)
		    }, [])
		},
		debouncedCalculateIncome() {
			clearTimeout(this.debounceTimer);
			this.debounceTimer = setTimeout(() => {
				this.calculateIncome();
			}, 1000); // 输入停止1秒后执行
		},
		addPackage() {
			this.showPopup = true;
		},
		setShareType(e) {
			this.shareType = Number(e.detail.value)
		},
		setImplementType(e) {
			this.implementType = Number(e.detail.value)
		},
		async calculateIncome() {
			if (!this.activityId) return;
			
			const shareValid = this.shareType === 1 
				? !!this.shareRatio && this.shareRatio > 0 
				: !!this.shareFixed && this.shareFixed > 0;
			
			const implementValid = this.implementType === 1 
				? !!this.implementRatio && this.implementRatio > 0 
				: !!this.implementFixed && this.implementFixed > 0;

			if (!shareValid || !implementValid) {
				this.minProfit = null;
				this.maxProfit = null;
				return;
			}

			const params = {
				id: this.activityId,
				share_type: this.shareType,
				implement_type: this.implementType,
				share_rate: this.shareType === 1 ? this.shareRatio : undefined,
				share_money: this.shareType === 2 ? this.shareFixed : undefined,
				implement_rate: this.implementType === 1 ? this.implementRatio : undefined,
				implement_money: this.implementType === 2 ? this.implementFixed : undefined,
				spec_value: this.specList,
				spec_value_list: this.activitySpecs.spec_value_list
			}
			// 过滤未定义的参数
			const filteredParams = Object.fromEntries(
				Object.entries(params).filter(([_, v]) => v !== undefined)
			);

			try {
				this.loading = true;
				const res = await activityIncome(filteredParams);
				
				
					this.minProfit = res.min_profit;
					this.maxProfit = res.max_profit;
				
			} catch (e) {
				uni.showToast({ title: '收益计算失败', icon: 'none' });
			} finally {
				this.loading = false;
			}
		},
		async trainerList() {
			try {
				const res = await trainerList();
				if (res && res.lists && res.lists.length > 0) {
					this.trainerId = res.lists[0].id;
					console.log('获取到的训练师 id:', this.trainerId);
				} else {
					console.log('未找到有效的训练师数据');
				}
			} catch (error) {
				console.error('获取训练师列表失败:', error);
			}
		},
		async submit() {
			// 在提交时增加参数
			const params = {
				id: this.activityId,
				terminal: this.$store.state.app.client,
				share_type: this.shareType,
				implement_type: this.implementType,
				share_rate: this.shareType === 1 ? this.shareRatio : undefined,
				share_money: this.shareType === 2 ? this.shareFixed : undefined,
				implement_rate: this.implementType === 1 ? this.implementRatio : undefined,
				implement_money: this.implementType === 2 ? this.implementFixed : undefined,
				coach_id: this.trainerId,
				spec_value: this.specList,
				spec_value_list: this.activitySpecs.spec_value_list
			}

			// 过滤并提交
			const filteredParams = Object.fromEntries(
				Object.entries(params).filter(([_, v]) => v !== undefined)
			);

			try {
				if (this.activityState === 0) {
					let result = await publishActivity(filteredParams);
					console.log('publish',result)
					this.$Router.push({
						path: `/pages/payment/payment`,
						query: {
							from: 'order',
							order_id: result.order_id
						}
					})
				}
				this.$emit('next');
			} catch (e) {
				// 错误处理
			}
		},
		// 添加规格项
		addSpecItem() {
			if (this.specList.length >= 3) {
				uni.showToast({
					title: '最多添加3个规格',
					icon: 'none'
				});
				return;
			}
			this.specList.push({
				id: '',
				name: '',
				spec_list: [
						{
								id: '',
								value: '',
								image: ''
						}
				]
			});
		},

		// 删除规格
		deleteSpec(index) {
			this.specList.splice(index, 1);
		},

		// 添加规格值
		addSpecValue(specIndex) {
			this.specList[specIndex].spec_list.push({
					id: '',
					value: '',
			})
		},

		// 删除规格值
		deleteValue(specIndex, valueIndex) {
			this.specList[specIndex].spec_list.splice(valueIndex, 1);
		},

		// 确认规格设置
		confirmSpecs() {
			// 这里添加验证逻辑
			if (!this.validateSpecs()) {
				return;
			}

			// 处理数据并关闭弹窗
			this.showPopup = false;
			// TODO: 处理确认后的数据
		},

		// 验证规格数据
		validateSpecs() {
			if (this.specList.length === 0) {
				uni.showToast({
					title: '请至少添加一个规格',
					icon: 'none'
				});
				return false;
			}
			// 添加其他验证逻辑
			return true;
		},
		formatSpecValues(str) {
			return str.split(',').join(' + ')
		}
	},
	beforeDestroy() {
		clearTimeout(this.debounceTimer);
	}
};
</script>

<style lang="scss" scoped>
// 样式部分保持不变
.step-item {
	padding: 30rpx;
	background: #f5f5f5;
}

.activity-title {
	display: flex;
	flex-direction: column;
	font-weight: 500;
	font-size: 38rpx;
	color: #000000;
	margin: 20rpx 0;

	.title-text {
		margin-bottom: 32rpx;
		font-weight: 500;
		font-size: 38rpx;
		color: #000000;
	}
	.fee-note {
		font-size: 24rpx;
		color: #999;
		margin-left: 10rpx;
	}
}

.section {
	background: #ffffff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;

	.section-title {
		font-size: 28rpx;
		font-weight: 500;
		margin-bottom: 20rpx;
		position: relative;

		&::before {
			border: 1rpx dashed #0dc160;
			content: '';
			width: 6rpx;
			height: 28rpx;
			background: #0dc160;
			position: absolute;
			left: -30rpx;
			top: 50%;
			transform: translateY(-50%);
		}
	}
}

.package-list {
	.empty-tips{
		padding: 10rpx;
		text-align: center;
	}
	.package-item {
		background: linear-gradient(180deg, #fbfffd 0%, #f5fff9 100%);
		border-radius: 10rpx;
		border: 1rpx dashed #0dc160;
		border-radius: 8rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;

		.requirement {
			font-size: 26rpx;
			color: #333;
		}

		.price-info {
			margin-top: 10rpx;

			.original-price {
				color: #999;
				text-decoration: line-through;
				margin-right: 10rpx;
			}

			.current-price {
				color: #ff6b00;
				font-weight: bold;
			}

			.discount {
				color: #ff6b00;
				margin: 0 10rpx;
			}

			.stock {
				color: #999;
				float: right;
			}
		}
	}
}

.add-package {
	display: flex;
	align-items: center;
	justify-content: center;
	height: 80rpx;
	border: 2rpx solid #0dc160;
	border-radius: 8rpx;
	color: #0dc160;
	font-size: 28rpx;

	text {
		margin-left: 10rpx;
	}
}

.profit-settings {
	.setting-group {
		margin-bottom: 30rpx;
		padding: 20rpx;
		background: #f8f8f8;
		border-radius: 8rpx;
	}

	.sub-title {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 20rpx;
	}

	.radio-group {
		display: flex;
		gap: 40rpx;
		flex-wrap: wrap;
	}

	.radio-item {
		display: flex;
		align-items: center;
	}

	.radio-item radio {
		transform: scale(0.9);
		margin-right: 8rpx;
	}

	.input-group {
		margin-top: 20rpx;
		display: flex;
		align-items: center;
		gap: 20rpx;
		
		input {
			flex: 1;
			height: 70rpx;
			border: 1rpx solid #eee;
			border-radius: 8rpx;
			padding: 0 20rpx;
		}
		
		.unit {
			width: 60rpx;
			text-align: center;
		}
	}

	.profit-range {
		display: flex;
		align-items: center;

		input {
			width: 200rpx;
			height: 80rpx;
			border: 2rpx solid #e5e5e5;
			border-radius: 8rpx;
			padding: 0 20rpx;
		}

		.separator {
			margin: 0 20rpx;
		}
	}
}

.coupon-settings {
	display: flex;
	flex-direction: column;
	.coupon-item {
		display: flex;
		align-items: center;
	}
	.enable-coupon {
		margin-right: 20rpx;
	}

	input {
		width: 200rpx;
		height: 80rpx;
		border: 2rpx solid #e5e5e5;
		border-radius: 8rpx;
		padding: 0 20rpx;
	}

	.unit {
		margin-left: 10rpx;
	}
}

.submit-btn {
	margin-top: 40rpx;

	.btn-primary {
		width: 100%;
		height: 90rpx;
		background: #0dc160;
		color: #ffffff;
		border-radius: 45rpx;
		font-size: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
}

.placeholder {
	color: #999;
	font-size: 26rpx;
}

/* 弹框相关样式 */
.popup-container {
	background-color: #fff;
	border-radius: 24rpx 24rpx 0 0;
	padding-bottom: env(safe-area-inset-bottom);
}

.popup-header {
	text-align: center;
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	border-bottom: 1rpx solid #eee;

	.popup-wrapper {
		flex: 1;
		text-align: center;
	}
	.popup-title {
		font-size: 34rpx;
		color: #000000;
		line-height: 34rpx;
		text-align: center;
		font-weight: 500;
	}

	.close-icon {
		padding: 10rpx;
	}
}

.popup-content {
	padding: 30rpx;
	max-height: 70vh;
	overflow-y: auto;
}

.spec-section,
.price-section {
	margin-bottom: 30rpx;

	.section-header {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;

		.limit-text {
			font-size: 24rpx;
			color: #999;
			margin-left: 10rpx;
		}

		.add-spec {
			margin-left: auto;
			display: flex;
			align-items: center;
			color: #0dc160;
			font-size: 28rpx;
		}
	}
}

.spec-list {
	.spec-item {
		margin-bottom: 30rpx;
		background: #FFFFFF;
		
		.spec-name-section {
			margin-bottom: 20rpx;
			
			.spec-name-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 16rpx;
				
				text {
					font-size: 28rpx;
					color: #000000;
				}
			}
			
			.spec-name-input {
				width: 100%;
				height: 70rpx;
				border: 1rpx solid #eee;
				border-radius: 8rpx;
				padding: 0 20rpx;
				box-sizing: border-box;
			}
		}
		
		.spec-values-section {
			.spec-values-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 16rpx;
				
				text {
					font-size: 28rpx;
					color: #000000;
				}
				
				.add-value {
					color: #0dc160;
					font-size: 28rpx;
				}
			}
			
			.value-list {
				display: flex;
				flex-direction: column;
				gap: 16rpx;
				
				.value-item {
					display: flex;
					align-items: center;
					gap: 10rpx;
					
					input {
						flex: 1;
						height: 70rpx;
						border: 1rpx solid #eee;
						border-radius: 8rpx;
						padding: 0 20rpx;
						box-sizing: border-box;
					}
					
					image {
						flex-shrink: 0;
					}
				}
			}
		}
	}
}

.price-table {
	border: 1rpx solid #eee;
	border-radius: 8rpx;

	.table-header {
		display: grid;
		grid-template-columns: 2fr 1fr 1fr;
		background-color: #f8f8f8;
		padding: 20rpx;
		text-align: center;
		font-size: 28rpx;
	}

	.table-row {
		display: grid;
		grid-template-columns: 2fr 1fr 1fr;
		padding: 20rpx;
		border-top: 1rpx solid #eee;
		align-items: center;

		input {
			height: 60rpx;
			border: 1rpx solid #eee;
			border-radius: 8rpx;
			padding: 0 20rpx;
			text-align: center;
		}
	}
}

.popup-footer {
	padding: 20rpx 30rpx;
	border-top: 1rpx solid #eee;

	.confirm-btn {
		width: 100%;
		height: 80rpx;
		background: #0dc160;
		color: #fff;
		border-radius: 40rpx;
		font-size: 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
}

.income-result {
	padding: 20rpx;
	background: #f8f8f8;
	border-radius: 8rpx;
	color: #0DC160;
	font-size: 28rpx;
}

.loading-wrapper {
	display: flex;
	align-items: center;
	padding: 20rpx;
	
	.loading-text {
		margin-left: 20rpx;
		color: #666;
	}
}

/* 新增水平布局样式 */
.horizontal {
	display: inline-flex !important;
	margin-right: 40rpx;
}

.income-tips {
	padding: 20rpx;
	color: #999;
	font-size: 24rpx;
	text-align: center;
}
</style>
